/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import fs from 'fs';
import path from 'path';

import { CodeType } from '../../enum/code-type-enum.js';
import { CodeModel } from '../code-source/code-model.js';
import { CodeModelImpl } from '../code-source/code-model-impl.js';
import { CoreResModelImpl } from '../res/core-res-model-impl.js';

import { SourceSetModel } from './source-set-model.js';

/**
 * module中每个target对应的一个sourceSet对象
 *
 * @since 2022/2/24
 */
export abstract class CoreSourceSetImpl implements SourceSetModel {
  protected readonly sourceSetRoot: string;
  protected readonly codeMap: Map<CodeType, CodeModel>;
  protected readonly targetResModel: CoreResModelImpl;

  constructor(sourceSetRoot: string, targetResModel: CoreResModelImpl) {
    this.sourceSetRoot = sourceSetRoot;
    this.codeMap = this.initCodeMap();
    this.targetResModel = targetResModel;
  }

  getSourceSetRoot(): string {
    return this.sourceSetRoot;
  }

  getCodeMap(): Map<CodeType, CodeModel> {
    return this.codeMap;
  }

  getTargetResPath(): string {
    return this.targetResModel.getResourcePath();
  }

  private initCodeMap(): Map<CodeType, CodeModel> {
    const map = new Map<CodeType, CodeModel>();

    for (const code of Object.values(CodeType)) {
      if (typeof code !== 'string') {
        continue;
      }
      const codeDir: string = code.toString().toLowerCase();
      const codePath: string = path.resolve(this.sourceSetRoot, codeDir);

      if (fs.existsSync(codePath)) {
        map.set(code, new CodeModelImpl(codePath, code));
      }
    }
    return map;
  }

  abstract getTargetSourceSetModuleName(): string | undefined;
}
